/**
 * Created by Mars on 2015/11/18.
 */
app.config(function ($routeProvider, $locationProvider) {
    $routeProvider.
    when('/grid', {
        templateUrl: 'grid/index.html',
        controller: ''
    }).
    when('/grid/cangshun', {
        templateUrl: 'grid/cangshun.html',
        controller: 'gridController'
    }).
    when('/grid/cangyi', {
        templateUrl: 'grid/cangyi.html',
        controller: 'gridController'
    }).
    when('/grid/yongning', {
        templateUrl: 'grid/yongning.html',
        controller: 'gridController'
    })
});

function mapService(){

    return {
        map  : '',
        minZoom  : '2',
        maxZoom  : '20',
        mgr  : '',
        init : function( domId ){
            $('#'+domId).show();
            this.map = new BMap.Map(domId);

            var point = new BMap.Point(120.381163, 36.093801);
            this.map.centerAndZoom(point,15);
            this.map.enableScrollWheelZoom();

            this.mgr = new BMapLib.MarkerManager(this.map,{borderPadding: 200,maxZoom: 20,trackMarkers: true});

        }

        ,markers : function( point ){
            var position = point;
            var markers = [];
            var realBounds = this.mgr._getRealBounds();
            for( var i = 0; i < position.length; i ++ ){
                var point = new BMap.Point(position[i].lng, position[i].lat);
                var marker = new BMap.Marker(point);
                markers.push({
                    point : point,
                    marker :marker
                });
                this.mgr.addMarker(marker, this.minZoom, this.maxZoom);
            }
            //this.clickMarkers( markers, fn );
            this.mgr.showMarkers();
        }
        ,clickMarkers : function( markers, fn ){
            var thisMap = this.map;
            var thisMgr = this.mgr;
            for( var i = 0; i < markers.length; i ++){
                markers[i].marker.addEventListener("click", function(){

                    var opts = {
                        width : 250,     // 信息窗口宽度
                        height: 100,     // 信息窗口高度
                        title : "Hello"  // 信息窗口标题
                    };
                    var infoWindow = new BMap.InfoWindow("World", opts);  // 创建信息窗口对象
                    thisMap.openInfoWindow(infoWindow, this.point);      // 打开信息窗口
                });
                markers[i].marker.addEventListener("dragend", function(){

                    console.log("气球坐标变更为：" + this.point.lng + ", " + this.point.lat);
                    if( typeof fn == 'function' ){
                        fn(this.point);
                    }
                });
                (function(mk,n){
                    mk.addEventListener("dblclick", function(){

                        if(n == 0){ //删掉为0的marker ， 会出现bug， 暂时保留
                            console.log(n);
                            return;
                        }
                        console.log(mk);
                        console.log(markers);
                        thisMgr.removeMarker(mk);      // 打开信息窗口
                    });
                })(markers[i].marker,i)
            }
        },
        setPath:function(points){
            this.map.enableScrollWheelZoom();
            this.map.centerAndZoom(points[0],15);

            //var polyline = new BMap.Polyline();   //创建折线
            //polyline.setPath(points);
            //polyline.setStrokeColor('red');
            //polyline.setStrokeOpacity(1);
            //polyline.setStrokeWeight(2);
            //polyline.setStrokeStyle('dashed');
            //var polyline = new BMap.Polyline([
            //    new BMap.Point(116.399, 39.910),
            //    new BMap.Point(116.405, 39.920),
            //    new BMap.Point(116.423493, 39.907445)
            //], {strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});   //创建折线
            var curve = new BMapLib.CurveLine(points, {strokeColor:"blue", strokeWeight:3, strokeOpacity:0.5}); //创建弧线对象
            this.map.addOverlay(curve); //添加到地图中

            //this.map.addOverlay(polyline);   //增加折线
        },
        clearMarkers : function(){
            this.mgr.clearMarkers()
        }
    };
}
app.factory('mapService', mapService);
app.controller('gridController', ['$scope', '$rootScope', '$window', '$location', '$http', '$routeParams', 'mapService',gridController]);
function gridController ($scope,$rootScope,$window,$location,$http,$routeParams,mapService){
    $scope.filter = {};
    //mapService.init("map");
    $scope.searchInfo = function(){
        var start_time = angular.element("#start_time").val();
        var end_time = angular.element("#end_time").val();
        var date = new Date();
        if(typeof start_time == "undefined"||start_time == ""){
            start_time = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+"00:00:00";
        }
        if(typeof end_time == "undefined"||end_time == ""){
            end_time = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+"23:59:59";
        }

        var param = {
            cardid:$scope.filter.idCard
            //start_time : start_time,
            //end_time : end_time
        }
        baas_yl.call({
            'http': $http,
            'method': 'get',
            'uri': 'archives/archives/search/track/data',
            'data':param,
            'success': function(d) {
                var points = []
                if(d.status == 1){
                    angular.forEach(d.list,function(data,list,count){

                        var point = new BMap.Point(data.longitude, data.latitude);

                        points.push(point);
                    });
                    mapService.markers(points);
                    mapService.setPath(points);
                }
            }
        })
    }

    angular.element('#map').click(function (event) {
        var window = angular.element('#pop');
        var trigger = angular.element(event.target);
        if (trigger.hasClass('pop_trigger')) {
            var urlArray = $location.$$path.split('/');
            var areaString = urlArray[urlArray.length - 1];
            var jsonBase = $location.$$protocol + '://' + $location.$$host + '/admin/grid/';
            var jsonPath = jsonBase + areaString + '.json';
            $http.get(jsonPath).success(function(data) {
                var dataList = data.list;
                var partString = trigger.children('.maphover').text();
                for (var i = 0; i < dataList.length; i++) {
                    if (dataList[i].title === partString) {
                        $scope.pop = dataList[i];
                        trigger.append(window);
                        window.css('display', 'inline-block');
                        break;
                    }
                }
            });
        } else if (trigger.parents('#pop').length == 0) {
            window.css('display', 'none');
        }
    });
    angular.element('#tab01').click(function () {
        angular.element(this).siblings().removeClass("current");
        angular.element(this).addClass("current");
        angular.element("#ul02").removeClass("cur");
        angular.element("#ul01").addClass("cur");
    });
    angular.element('#tab02').click(function () {
        angular.element(this).siblings().removeClass("current");
        angular.element(this).addClass("current");
        angular.element("#ul01").removeClass("cur");
        angular.element("#ul02").addClass("cur");
    });
}